<?php

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class ImportPCMenu extends Command
{
    protected function configure()
    {
        $this->setName('importMenu:PC')
            ->addOption('path', null, Option::VALUE_REQUIRED, 'route file path')
            ->setDescription('import PC route to  Menu');
    }

    protected function execute(Input $input, Output $output)
    {
        if ($input->hasOption('path')) {
            $path = $input->getOption('path');
        } else {
            $path = \think\facade\Env::get('ROOT_PATH') . 'route.json';
        }
        $router = json_decode(file_get_contents($path), true);
        $model = new \app\admin\model\Menu();
        $list = array_map('build', $router);
        $ch = [];
        foreach ($list as $k => $item) {
            if (isset($item['children'])) {
                foreach ($item['children'] as $cc) {
                    $cc['parent_id'] = $model->where('name', $cc['parent'])->find()['id'];
                    $cc['ua'] = 'pc';
                    $cc['permission_id'] = 0;
                    $ch[] = $cc;
                }
                unset($list[$k]['children']);
            }
        }
        try {
            if ($model->saveAll($list) && $model->saveAll($ch)) {
                $output->writeln("import,done");
            }
        } catch (\Exception $e) {
            $output->writeln("import, fail");
        }
    }

    private function build($v)
    {
        $o['name'] = !isset($v['path']) ? null : $v['path'];
        $o['title'] = !isset($v['meta']['title']) ? null : $v['meta']['title'];
        $o['icon'] = !isset($v['meta']['icon']) ? null : $v['meta']['icon'];
        $o['hidden'] = !isset($v['meta']['hidden']) ? null : $v['meta']['hidden'];
        $o['ua'] = 'pc';
        $o['permission_id'] = 0;
        if (isset($v['children'])) {
            $o['parent_id'] = 0;
            $o['children'] = array_map(function ($c) use ($o) {
                $y['name'] = $o['name'] . '/' . $c['path'];
                $y['title'] = $c['meta']['title'];
                $y['icon'] = $c['meta']['icon'];
                $y['hidden'] = $c['meta']['hidden'];
                $y['parent'] = $o['name'];
                return $y;
            }, $v['children']);
        }
        return $o;
    }
}
